﻿(function () {
    appModule.controller('common.views.notificationManage.index', [
        '$scope', '$uibModal', 'uiGridConstants', 'appUserNotificationHelper', 'abp.services.app.notification', '$stateParams',
        function ($scope, $uibModal, uiGridConstants, appUserNotificationHelper, notificationService, $stateParams) {
            var vm = this;

            $scope.$on('$viewContentLoaded', function () {
                App.initAjax();
            });

            vm.loading = false;
            vm.readStateFilter = 'ALL';
            vm.filterText = $stateParams.filterText || '';

            //制作权限组，进行页面权限的判断 
            vm.permissions = {
                create: abp.auth.hasPermission("Pages.Notification.CreateNotification"),
                edit: abp.auth.hasPermission("Pages.Notification.EditNotification"),
                'delete': abp.auth.hasPermission("Pages.Notification.DeleteNotification"),
                detail: abp.auth.hasPermission("Pages.Notification.DetailNotification")
            };

            //请求参数，默认用于分页
            vm.requestParams = {
                permission: '',
                role: '',
                skipCount: 0,
                //这里是个常量文件，如果你没有找到这个常量文件，那么就手动改成10吧
                maxResultCount: app.consts.grid.defaultPageSize,
                sorting: null
            };

            vm.gridOptions = {
                enableHorizontalScrollbar: uiGridConstants.scrollbars.WHEN_NEEDED,
                enableVerticalScrollbar: uiGridConstants.scrollbars.WHEN_NEEDED,
                paginationPageSizes: app.consts.grid.defaultPageSizes,
                paginationPageSize: app.consts.grid.defaultPageSize,
                useExternalPagination: true,
                enableSorting: false,
                appScopeProvider: vm,
                rowTemplate: '<div ng-repeat="(colRenderIndex, col) in colContainer.renderedColumns track by col.colDef.name" class="ui-grid-cell" ng-class="{ \'ui-grid-row-header-cell\': col.isRowHeader, \'notification-read\' : row.entity.state == \'READ\' }"  ui-grid-cell></div>',
                columnDefs: [
                    {
                        name: app.localize('Notification'),
                        field: 'text',
                        minWidth: 500,
                        cellTemplate:
                            '<div class=\"ui-grid-cell-contents\">' +
                            //'  <a ng-if="row.entity.url" ng-href="{{row.entity.url}}" title="{{row.entity.text}}">{{row.entity.text}}</a>' +
                            '  <span title="{{row.entity.data.message}}">{{row.entity.text}}</span>' +
                            '</div>'
                    },
                    {
                        name: app.localize('NotificationName'),
                        field: 'name',
                        minWidth: 100
                    },
                    {
                        name: app.localize('Status'),
                        field: 'sex',
                        cellTemplate:
                            '<div class=\"ui-grid-cell-contents\">' +
                            '  <span ng-show="row.entity.state" class="label label-default">' + app.localize('Read') + '</span>' +
                            '  <span ng-show="!row.entity.state" class="label label-success">' + app.localize('Unread') + '</span>' +
                            '</div>',
                        width: 80
                    },
                    {
                        name: app.localize('CreationTime'),
                        field: 'time',
                        cellFilter: 'momentFormat: \'YYYY-MM-DD HH:mm:ss\'',
                        width: 200
                    },
                    {
                        //这里是在处理多语言本地化的问题，如果你这里报错。那么手动修改名字吧。
                        name: app.localize('Actions'),
                        enableSorting: false,
                        width: 120,
                        cellTemplate:
                            '<div class=\"ui-grid-cell-contents\">' +
                            '  <div class="btn-group dropdown" uib-dropdown="" dropdown-append-to-body>' + '    <button class="btn btn-xs btn-primary blue" uib-dropdown-toggle="" aria-haspopup="true" aria-expanded="false"><i class="fa fa-cog"></i> ' + app.localize('Actions') + ' <span class="caret"></span></button>' +
                            '    <ul uib-dropdown-menu>' +
                            '      <li><a ng-if="grid.appScope.permissions.detail" ng-click="grid.appScope.detail(row.entity)">' + app.localize('Detail') + '</a></li>' +

                            '      <li><a ng-if="grid.appScope.permissions.delete" ng-click="grid.appScope.delete(row.entity)">' + app.localize('Delete') + '</a></li>' +
                            '    </ul>' +
                            '  </div>' +
                            '</div>'
                    },
                ],
                // ui-grid进行API注册渲染数据。
                onRegisterApi: function (gridApi) {
                    $scope.gridApi = gridApi;
                    $scope.gridApi.core.on.sortChanged($scope, function (grid, sortColumns) {
                        if (!sortColumns.length || !sortColumns[0].field) {
                            vm.requestParams.sorting = null;
                        } else {
                            vm.requestParams.sorting = sortColumns[0].field + ' ' + sortColumns[0].sort.direction;
                        }
                        vm.getNotifications();
                    });
                    //配置UI-grid的 API参数
                    gridApi.pagination.on.paginationChanged($scope, function (pageNumber, pageSize) {
                        vm.requestParams.skipCount = (pageNumber - 1) * pageSize;
                        vm.requestParams.maxResultCount = pageSize;
                        //执行查询语句
                        vm.getNotifications();
                    });
                },
                data: []
            };

            //创建功能
            vm.createNotification = function () {
                var _templateUrl = '~/App/common/views/notificationManage/createOrEditModal.cshtml';
                var _controller = 'common.views.notificationManage.createOrEditModal as vm';
                openCreateOrEditNotificationModal(null, _templateUrl, _controller);
            };

            //详情功能
            vm.detail = function (notification) {
                var _templateUrl = '~/App/common/views/notificationManage/detail.cshtml';
                var _controller = 'common.views.notificationManage.detail as vm';
                openCreateOrEditNotificationModal(notification.id, _templateUrl, _controller);
            };

            //删除方法
            vm.delete = function (notification) {
                abp.message.confirm(
                    app.localize('NotificationDeleteWarningMessage', notification.name),
                    function (isConfirmed) {
                        if (isConfirmed) {
                            notificationService.deleteUserNotificationByIdAsync({
                                tenantId: 1,
                                userNotificationId: notification.id
                            }).then(function () {
                                vm.getNotifications();
                                abp.notify.success(app.localize('SuccessfullyDeleted'));
                            });
                        }
                    }
                );
            };

            //打开模态框，进行创建或者编辑的功能操作
            function openCreateOrEditNotificationModal(notificationId, _templateUrl, _controller) {
                var modalInstance = $uibModal.open({
                    templateUrl: _templateUrl,
                    controller: _controller,
                    backdrop: 'static',
                    resolve: {
                        notificationId: function () {
                            return notificationId;
                        }
                    }
                });

                modalInstance.result.then(function (result) {
                    vm.getNotifications();
                });
            }

            vm.getNotifications = function () {
                vm.loading = true;
                notificationService.getPagedUserNotificationsAsync($.extend({ filter: vm.filterText }, vm.requestParams)).then(function (result) {
                    vm.gridOptions.totalItems = result.data.totalCount;

                    vm.gridOptions.data = _.map(result.data.items, function (item) {
                        var data = appUserNotificationHelper.formatExtend(item, false);
                        if (data.state == "UNREAD") {
                            data.state = false;
                        }
                        else {
                            data.state = true;
                        }
                        return data;
                    });
                }).finally(function () {
                    vm.loading = false;
                });
            };

            vm.getNotifications();
        }
    ]);
})();